using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Guide;
using B.S.NewMedical.Api.Read.DTOS.Guide;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Guide
{
    /// <summary>
    /// 获取就医指南文章列表处理器
    /// </summary>
    public class GetGuideArticlesHandler : IRequestHandler<GetGuideArticlesCommand, ApiResult<List<GuideArticleDto>>>
    {
        private readonly IBaseRepository<GuideArticle> _articleRepository;
        private readonly IBaseRepository<GuideCategory> _categoryRepository;
        private readonly ILogger<GetGuideArticlesHandler> _logger;
        private readonly IMapper _mapper;

        public GetGuideArticlesHandler(
            IBaseRepository<GuideArticle> articleRepository,
            IBaseRepository<GuideCategory> categoryRepository,
            ILogger<GetGuideArticlesHandler> logger,
            IMapper mapper)
        {
            _articleRepository = articleRepository;
            _categoryRepository = categoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<GuideArticleDto>>> Handle(GetGuideArticlesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取就医指南文章列表，分类ID：{CategoryId}", request.CategoryId);

                // 构建基础查询
                var query = _articleRepository.GetAll().Where(a => !a.IsDeleted);

                // 按分类筛选
                if (request.CategoryId.HasValue)
                {
                    query = query.Where(a => a.CatId == request.CategoryId.Value);
                }

                // 获取所有文章，按创建时间降序排序
                var articles = await query
                    .OrderByDescending(a => a.CreatedAt)
                    .ToListAsync(cancellationToken);

                // 获取所有相关的分类
                var categoryIds = articles.Select(a => a.CatId).Distinct().ToList();
                var categories = await _categoryRepository.GetAll()
                    .Where(c => !c.IsDeleted && categoryIds.Contains(c.Id))
                    .ToListAsync(cancellationToken);

                // 手动映射到DTO并添加分类名称
                var result = articles.Select(a => new GuideArticleDto
                {
                    Id = a.Id,
                    CatId = a.CatId,
                    CategoryName = categories.FirstOrDefault(c => c.Id == a.CatId)?.Name ?? "未知分类",
                    Title = a.Title,
                    CoverImg = a.CoverImg,
                    ViewCnt = a.ViewCnt,
                    CreatedAt = a.CreatedAt
                }).ToList();

                return new ApiResult<List<GuideArticleDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取就医指南文章列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取就医指南文章列表时发生异常");
                return new ApiResult<List<GuideArticleDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取就医指南文章列表失败：" + ex.Message
                };
            }
        }
    }
} 